﻿using UnityEngine;

//背景控制器
public class RepeatBackground : MonoBehaviour {

	public GameObject skyAndGrass;//草坪和土地对象
	public GameObject grass;
	private float moveHorizontal = 0f;
	private Vector3 bgPosition = new Vector3(0, 0, 0);
	private readonly int bgSize = 3;//生成几个背景，此处的数字一定要大于等于2
	private GameObject[] bgArry;//背景数组
	private int bgArryIndex = 0;//数组下标
	private int bgCount = 1;//背景數量
	private float skyAndGrassWidth;
	private static object locker = new object();

	// Use this for initialization
	void Start() {
		bgArry = new GameObject[bgSize];
		skyAndGrassWidth = grass.GetComponent<BoxCollider2D>().size.x;
		for (int i = 0; i < bgSize; i++) {
			if (i == 0)
				bgPosition = new Vector3(0, 0, 0);
			else
				bgPosition = new Vector3(skyAndGrassWidth, 0, 0);
			bgArry[i] = Instantiate(skyAndGrass, bgPosition, Quaternion.identity);
		}
		//背景移动
		GameController.initialize.gameObjectMove(bgArry[0]);
	}

	// Update is called once per frame
	void Update() {
		if (GameController.initialize.gameIsOver) {
			stop();
			return;
		}
		//每100帧执行一次
		if (Time.frameCount % 100 == 0) {
			//当前背景移动的水平距离
			moveHorizontal = Mathf.Abs(bgArry[bgCount - 1].transform.position.x) % skyAndGrassWidth;
			//Debug.Log(moveHorizontal);
			//背景自动移动,当(skyAndGrassWidth - moveHorizontal) <= 15 并且没有锁的情况下才可以继续执行
			if ((skyAndGrassWidth - moveHorizontal) <= 15) {
				//需要移动的背景墙的下标(需要显示移动的背景是当前背景的下个背景)
				bgArryIndex = calcIndex(bgCount);
				var position = new Vector3(skyAndGrassWidth - moveHorizontal, transform.position.y, 0);
				if (bgArry[bgArryIndex] != null) {
					bgArry[bgArryIndex].transform.position = position;
					GameController.initialize.gameObjectMove(bgArry[bgArryIndex]);//背景移动
				}
				bgCount++;
				if (bgCount > bgSize)
					bgCount = 1;
			}
		}
	}

	private int calcIndex(int index) {
		if ((bgCount - 1) == 0)
			return 1;
		else if ((bgCount - 1) == 1)
			return 2;
		else if ((bgCount - 1) == 2)
			return 0;
		return 0;
	}

	//停止移动
	private void stop() {
		for (int i = 0; i < bgSize; i++) {
			bgArry[i].GetComponent<Rigidbody2D>().velocity = Vector2.zero;
		}
	}

}
